package servlet;

import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;
import jnr.posix.util.DefaultPOSIXHandler;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;


@WebServlet("/MutationServlet")
public class MutationServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String path = "D:\\workspace\\idea\\PITest";

        String pitReportsPath = path + "\\target\\pit-reports";
        System.out.println("pitReportsPath is " + pitReportsPath);
        String pitReportsTargetPath = path + "\\target\\PITest\\pit-reports";
        System.out.println("pitReportsTargetPath is " + pitReportsTargetPath);

        delete(new File(pitReportsPath));

        POSIX posix = POSIXFactory.getPOSIX(new DefaultPOSIXHandler(),true);

        // 1. 获取并验证参数
        String[] mutators = request.getParameterValues("mutators");
        if (mutators == null || mutators.length == 0) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "至少选择一个算子");
            return;
        }

        // 3. 构建Maven命令
        String mutatorList = String.join(",", mutators);
        String mavenCommand = "mvn org.pitest:pitest-maven:mutationCoverage -Dmutators=" + mutatorList;

        // 4. 执行命令（此处模拟执行，实际生产环境需异步处理）
        String currentDir = System.getProperty("user.dir");
        System.out.println("Current working directory: " + currentDir);
        try {

            System.setProperty("user.dir", path);

            String currentDir2 = System.getProperty("user.dir");
            System.out.println("Current working directory: " + currentDir2);
            posix.chdir(currentDir2);

            Process process = Runtime.getRuntime().exec("cmd.exe /c " + mavenCommand);
            // 读取命令的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "执行失败");
                return;
            } else {
                // 读取错误输出流，获取错误信息
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String errorLine;
                while ((errorLine = errorReader.readLine()) != null) {
                    System.err.println(errorLine);
                }
                System.out.println("Failed with exit value: " + exitCode);
            }

            // 将报告复制到web中
            Path sourceDirectory = Paths.get(pitReportsPath);
            Path targetDirectory = Paths.get(pitReportsTargetPath);

            if (Files.exists(targetDirectory)) {
                delete(new File(pitReportsTargetPath));
            }

            if (!Files.exists(targetDirectory)) {
                Files.createDirectories(targetDirectory);
                System.out.println("文件夹已创建: " + targetDirectory);
            }

            try {
                // 遍历源目录中的所有文件和子目录
                Files.walk(sourceDirectory)
                        .forEach(sourcePath -> {
                            // 计算目标路径
                            Path targetPath = targetDirectory.resolve(sourceDirectory.relativize(sourcePath));
                            try {
                                // 如果当前路径是目录，则创建对应的目录
                                if (Files.isDirectory(sourcePath)) {
                                    Files.copy(sourcePath, targetPath, REPLACE_EXISTING);
                                } else {
                                    // 复制文件
                                    Files.copy(sourcePath, targetPath, REPLACE_EXISTING);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        });
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误");
            return;
        } finally {
            System.out.println("Current working directory: " + currentDir);
            System.setProperty("user.dir", currentDir);
            posix.chdir(currentDir);
        }

        String htmlPath = request.getContextPath() + "/pit-reports/index.html";
        response.sendRedirect(htmlPath);
    }

    public static void delete(File folder) {
        if(folder.isDirectory()) {
            File[] files = folder.listFiles();
            if(files != null) { // 如果文件夹为空，files可能为null
                for(File file : files) {
                    delete(file); // 递归删除子文件夹和文件
                }
            }
        }
        folder.delete(); // 删除空文件夹或者文件
    }
}